# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(tidyverse)
library(magrittr)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
)
opt <- parse_args(OptionParser(option_list = option_list))

parent <- paste0("./")
createWhenNoExist(parent)

workspacePath <- "../../"

dir <- str_c(workspacePath)
dirs <- list.dirs(dir, recursive = F) %>%
  keep(~str_detect(.x, "_vs_"))
treats <- basename(dirs)

tbf <- tibble()

for (treat in treats) {
  filePath <- str_c(workspacePath, treat, "/potential/Markers.csv")
  data <- read_csv(filePath) %>%
    select("Metabolite") %>%
    rename_at(vars(c("Metabolite")), function(x) {
      c(treat)
    })

  if (nrow(data) > 0) {
    data <- data %>%
      mutate(id = 1:n())
  }else {
    data <- data %>%
      add_column(id = NA)
  }

  if (ncol(tbf) == 0) {
    tbf <- data
  }else {
    tbf <- tbf %>%
      full_join(data, by = "id")
  }
}

columnNames <- treats
outData <- tbf
size <- length(columnNames)

tbf

if (length(columnNames) > 1 & length(columnNames) < 5) {
  for (i in size:2) {
    cn <- combn(columnNames, i)
    for (i in 1:ncol(cn)) {
      row <- cn[, i]
      columnName <- str_c(row, collapse = " & ")
      outData <- outData %>%
        mutate(!!columnName := {
          values <- row %>%
            map(function(t) {
              get(t)
            })
          x <- Reduce(intersect, values)
          x[1:n()]
        })
    }
  }
}else {
  for (i in size:size) {
    cn <- combn(columnNames, i)
    for (i in 1:ncol(cn)) {
      row <- cn[, i]
      columnName <- str_c(row, collapse = " & ")
      outData <- outData %>%
        mutate(!!columnName := {
          values <- row %>%
            map(function(t) {
              get(t)
            })
          x <- Reduce(intersect, values)
          x[1:n()]
        })
    }
  }
}

if (length(columnNames) < 5) {
  for (name in columnNames) {
    newName <- str_c(name, " only")
    outData <- outData %>%
      mutate(!!newName := {
        otherNames <- columnNames %>%
          discard(~.x %in% c(name))
        values <- c(name, otherNames) %>%
          map(function(t) {
            get(t)
          })
        x <- Reduce(setdiff, values)
        x[1:n()]
      })
  }
}


outData <- outData %>%
  mutate_all(function(x) {
    replace_na(x, "")
  })

if (length(columnNames) >= 5) {
  outData <- outData %>%
    select((size + 2), columnNames)
}else {
  outData <- outData %>%
    select(-c(1:(size + 1)))
}

outData
write_csv(outData, "Sig_Met_Venn_Data.csv")





